#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""网关列表"""
import asyncio
import json
import os
import time
from datetime import datetime
from time import sleep
import requests
from dotenv import load_dotenv
import common
import db

mysqldb = db.DbManager()
load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('ADMIN')
passworld = os.getenv('PWD')


# 获取登录后cookie
async def get_cookie(page):
    cookies_list = await page.cookies()
    cookies = ''
    for cookie in cookies_list:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    print(cookies)
    return cookies


def list_split(items, n):
    return [items[i:i + n] for i in range(0, len(items), n)]


def curl():
    cookie_str = "JSESSIONID=C800668DDA71827B670F50DD8D216AFE;"
    cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
    data = {
        'start': 0,
        'limit': 5000,
        'unitid': '4028fc8a7075cd2d017075d216b30006',
    }
    headers = {
        'referer': 'http://pfsc.agri.cn/',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
    }
    resp = requests.post(
        "http://pfsc.agri.cn/price_portal/pi-info-day/getIndexByLevel",
        headers=headers) # , cookies=cookies, data=data
    json_text = json.loads(resp.text)
    print(json_text)
    list_html = json_text['content']
    print(len(list_html))
    for i in range(0, len(list_html)):
        for v in range(0,len(list_html[i])):
            print(list_html[i][v])
            now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            info = {
                    "publishDate": list_html[i][v]['publishDate'],
                    "indexValue": list_html[i][v]['indexValue'],
                    "nextRecordValue": list_html[i][v]['nextRecordValue'],
                    "weightValue": list_html[i][v]['weightValue'],
                    "name": list_html[i][v]['indexName'],
                    "type": list_html[i][v]['indexType'],
            }
            print(info)
            find_info = mysqldb.table_select_one(table='agri_price', field="id",
                                                 where={"publishDate": list_html[i][v]['publishDate'],"name":list_html[i][v]['indexName']})
            # 存在数据则跳过
            if find_info:
                # 更新
                info['update_date'] = now_time
                mysqldb.table_update(table="agri_price", data=info,
                                     where={"publishDate": list_html[i][v]['publishDate'],"name":list_html[i][v]['indexName']})
            else:
                # 添加
                info['create_date'] = now_time
                mysqldb.table_insert(table='agri_price', data=info)

    sleep(1)


def growthRank():
    cookie_str = "JSESSIONID=C800668DDA71827B670F50DD8D216AFE;"
    cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
    data = {
        'start': 0,
        'limit': 5000,
        'unitid': '4028fc8a7075cd2d017075d216b30006',
    }
    headers = {
        'referer': 'http://pfsc.agri.cn/',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
    }
    resp = requests.post(
        "http://pfsc.agri.cn/price_portal/index/growthRanking?unitType=",
        headers=headers) # , cookies=cookies, data=data
    json_text = json.loads(resp.text)
    print(json_text)
    list_html = json_text['data']
    print(list_html)
    print(len(list_html))
    for i in range(0, len(list_html['names'])):
        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        info = {
                "name": list_html['names'][i],
                "avgPrice": list_html['avgPrice'][i],
                "codes": list_html['codes'][i],
                "publishDate": list_html['date'][i],
                "difAvgPrice": list_html['difAvgPrice'][i],
                "lastAvgPrice": list_html['lastAvgPrice'][i],
                "priceHbs": list_html['priceHbs'][i],
        }
        print(info)
        find_info = mysqldb.table_select_one(table='agri_growthrank', field="id",
                                             where={"publishDate": list_html['date'][i],"name":list_html['names'][i],"codes":list_html['codes'][i]})
        # 存在数据则跳过
        if find_info:
            # 更新
            info['update_date'] = now_time
            mysqldb.table_update(table="agri_growthrank", data=info,
                                 where={"publishDate": list_html['date'][i],"name":list_html['names'][i],"codes":list_html['codes'][i]})
        else:
            # 添加
            info['create_date'] = now_time
            mysqldb.table_insert(table='agri_growthrank', data=info)

    sleep(1)

class Egas:
    def __init__(self):
        self.url = "http://210.12.220.207:8003/adp/gate/getAllGate"
        # sql = 'SELECT i.orgId FROM devices_info where device_sn is null order by id desc limit 500'
        # mysqldb.execute(sql)
        # self.org_ids=mysqldb.cur.fetchall()
        asyncio.get_event_loop().run_until_complete(self.main())

    async def main(self):
        curl()
        # growthRanking数据
        growthRank()


Egas()
